#pragma once

#include <memory>
#include <unordered_map>
#include <string>
#include <typeindex>
#include <functional>
#include <stdexcept>
#include <iostream>
#include <mutex>


class DIContainer {
public:
    // 注册服务，使用默认构造函数
    template<typename T>
    static void register_factory() {
        auto& instance = get_instance(); // Access the singleton instance
        auto key = std::type_index(typeid(T));
        instance.factories_[key] = []() {
            return std::make_shared<T>();
        };
    }

    // 注册服务，使用自定义工厂函数
    template<typename T>
    static void register_factory(std::function<std::shared_ptr<T>()> factory) {
        auto& instance = get_instance(); // Access the singleton instance
        auto key = std::type_index(typeid(T));
        instance.factories_[key] = factory;
    }

    // 获取服务
    template<typename T>
    static std::shared_ptr<T> get() {
        return std::static_pointer_cast<T>(resolve<T>());
    }   

private:
    // 获取单例实例
    static DIContainer& get_instance() {
        static DIContainer instance; // 懒汉式单例
        return instance;
    }

    // 解析服务
    template<typename T>
    static std::shared_ptr<T> resolve() {
        auto& instance = get_instance(); // Access the singleton instance
        auto key = std::type_index(typeid(T));
        
        // Check if the instance is already resolved
        auto it = instance.resolved_instances_.find(key);
        if (it != instance.resolved_instances_.end()) {
            return std::static_pointer_cast<T>(it->second);
        }

        // If not resolved, create a new instance
        auto factory_it = instance.factories_.find(key);
        if (factory_it != instance.factories_.end()) {
            auto instance_ptr = factory_it->second();
            instance.resolved_instances_[key] = instance_ptr; // Store the resolved instance
           
            return std::static_pointer_cast<T>(instance_ptr);
        }
        
        throw std::runtime_error("Service not found");
    }

    DIContainer() = default; // 私有构造函数
    ~DIContainer() = default; // 私有析构函数
    DIContainer(const DIContainer&) = delete; // 禁止拷贝构造
    DIContainer& operator=(const DIContainer&) = delete; // 禁止赋值

    std::unordered_map<std::type_index, std::function<std::shared_ptr<void>()>> factories_;
    std::unordered_map<std::type_index, std::shared_ptr<void>> resolved_instances_; // 新增的 map
};